package cashpointer.mobile;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import cashpointer.mobile.dao.DAOFunctions;
import cashpointer.mobile.dao.DaoModel.Cashpoints;
import cashpointer.mobile.dao.DaoModel.Countries;
import cashpointer.mobile.dao.DaoModel.Owners;
import cashpointer.mobile.support.PreferencesManager;

public class FindedCashpointsActivity extends ListActivity {

	/**
	 * Opcje menu.
	 */
	static private final int MENU_QUIT = Menu.FIRST;
	
	//private static String LOG_TAG = "FindedCashpointsActivity";
	
	/**
     * The columns we are interested in from the database
     */
	private static final String[] CASHPOINTS_PROJECTION = new String[] {
    	Cashpoints._ID, // 0
    	Cashpoints.ADDRESS_CITY, // 1
    	Cashpoints.ADDRESS_STREET, // 2
    };
	
	private static final String[] COUNTRY_PROJECTION = new String[] {
    	Countries._ID, // 0
    };

	private static final String[] OWNER_PROJECTION = new String[] {
    	Owners._ID, // 0
    };
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Pobieram dane potrzebne do zbudowania warunku WHERE
		String city = PreferencesManager.getString(getApplicationContext(), PreferencesManager.LIST_CITY_CHOOSE, "");
		String street = PreferencesManager.getString(getApplicationContext(), PreferencesManager.LIST_STREET_CHOOSE, "");
		boolean onlyMarked = PreferencesManager.getBoolean(getApplicationContext(), PreferencesManager.LIST_ONLY_MARKED_CASHPOINTERS_CHOOSE, false);
		long regionId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.LIST_REGION_CHOOSE_ID, (long)0);
		long countryId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.LIST_COUNTRY_CHOOSE_ID, (long)0);
		
		// Budowanie warunku WHERE
		StringBuilder sb = new StringBuilder();
		String where =  null;
		sb.append(" 1 = 1 ");
		
		// Tylko ulubione
		if (onlyMarked) {
			sb.append(" AND " + Cashpoints.MARKED + " = 1"); 
		}
		
		// Sprawdzam czy wybrany powiat jest typu " wszystkie "
		boolean isCountryNONE = DAOFunctions.isCountryNONE(getApplicationContext(), (int)countryId);
		
		// Wybrane wojewodztwo i powiat
		if (regionId > 0 && !isCountryNONE) { // konkretny powiat w wojewodztwie
			sb.append(" AND " + Cashpoints.COUNTRY_ID + " = " + countryId);
		} else if (regionId > 0 && isCountryNONE) { // wszystkie z danego wojewodztwa
			// Tworze kursor
			String regionWhere = Countries.REGION_ID + "=" + regionId;
			Cursor countryCursor = managedQuery(Countries.CONTENT_URI, COUNTRY_PROJECTION, regionWhere, null, Countries.DEFAULT_SORT_ORDER);			

			// Bedzie przechowywal warunki OR dla powiatow
			StringBuilder countrySb = new StringBuilder();
			
			// Przegladanie kursora
			if (countryCursor.moveToFirst()) {
		        int idColumn = countryCursor.getColumnIndex(Cashpoints._ID);
		        
		        do {
		        	// Pole "_ID"
					int cursorId = countryCursor.getInt(idColumn);

					// Dodaje wyszukane ID
					countrySb.append(" OR " + Cashpoints.COUNTRY_ID + " = " + cursorId);
		        } while (countryCursor.moveToNext());
		    }
			
			// Zamykam kursor
			if (countryCursor != null) {
				countryCursor.close();
			}
			
			if (countrySb.length() > 0) {
				sb.append(" AND (1 = 0 " + countrySb.toString() + ") "); // 1 = 0 zawsze fausz, ale spelnia zadanie przy OR
			}
		}
		
		// Wybrani wlasciciele
		// Tworze kursor
		String ownerWhere = Owners.SELECTED + " = 1";
		Cursor ownerCursor = managedQuery(Owners.CONTENT_URI, OWNER_PROJECTION, ownerWhere, null, Owners.DEFAULT_SORT_ORDER);			

		// Bedzie przechowywal warunki OR dla wlascicieli
		StringBuilder ownerSb = new StringBuilder();
		
		// Przegladanie kursora
		if (ownerCursor.moveToFirst()) {
	        int idColumn = ownerCursor.getColumnIndex(Cashpoints._ID);
	        
	        do {
	        	// Pole "_ID"
				int cursorId = ownerCursor.getInt(idColumn);

				// Dodaje wyszukane ID
				ownerSb.append(" OR " + Cashpoints.OWNER_ID + " = " + cursorId);
	        } while (ownerCursor.moveToNext());
	    }
		
		// Zamykam kursor
		if (ownerCursor != null) {
			ownerCursor.close();
		}
		
		// Zawsze to dodaje poniewaz zawsze musi byc wybrany choc jeden wlasciciel
		sb.append(" AND (1 = 0 " + ownerSb.toString() + ") "); // 1 = 0 zawsze fausz, ale spelnia zadanie przy OR
		
		// Wybrane miasto i ulica
		if (!city.equals("") && !street.equals("")) {
			sb.append(" AND " + Cashpoints.ADDRESS_CITY_SIMPLE + " LIKE '%" + city + "%'");
			sb.append(" AND " + Cashpoints.ADDRESS_STREET_SIMPLE + " LIKE '%" + street + "%'");
		} else if (!city.equals("")) {
			sb.append(" AND " + Cashpoints.ADDRESS_CITY_SIMPLE + " LIKE '%" + city + "%'");
		} else if (!street.equals("")) {
			sb.append(" AND " + Cashpoints.ADDRESS_STREET_SIMPLE + " LIKE '%" + street + "%'");
		}

		// Generowanie stringu z warunkiem where
		where = sb.toString();
		//Log.i(LOG_TAG, where);
		
		// Podpiecie layout'u
		setContentView(R.layout.finded_cashpoints);
				
		// Zbudowanie cursora i do pobrania danych
		Cursor cursor = managedQuery(Cashpoints.CONTENT_URI, CASHPOINTS_PROJECTION, where, null, Cashpoints.DEFAULT_SORT_ORDER);
		
		// Utworzenie adaptera i pobranie danych z kursora
		startManagingCursor(cursor);
        
		String[] from = new String[] { Cashpoints.ADDRESS_CITY, Cashpoints.ADDRESS_STREET };
        int[] to = new int[] { R.id.text1, R.id.text2 };
        
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.finded_cashpoints_row, cursor, from, to);
        setListAdapter(notes);
		
        // Przy obecnym wygladzie wyszukiwanie itak nie dziala ;)
        getListView().setTextFilterEnabled(false);
	}

	/**
     * Funkcja budowania menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, MENU_QUIT, 0, getString(R.string.menu_exit)).setIcon(R.drawable.menu_close);
    	return true;
    }

    /**
     * Obsluga zdarzenia wybrania opcji z menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case MENU_QUIT:
        		quit();
        		return true;
        }
	    
        return false;
    }
    
    /**
     * Obsluga zdarzenia wybrania pozycji z listy
     */
    protected void onListItemClick(ListView l, View view, int position, long id) {
        super.onListItemClick(l, view, position, id);
        Intent intent = new Intent(this, CashpointActivity.class);
        intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_ID, id);
		startActivity(intent);
    }

    /**
     * Funkcja konczenia aplikacji.
     */
    private void quit() {
    	this.finish();
    }
}
